#include "FileNotificationClient.h"
#include <boost/date_time.hpp>
#include <sstream>
#include <fstream>
#include <direct.h>

FileNotificationClient::FileNotificationClient( const std::string& directoryName )
    :m_folderName( directoryName )
    ,m_counter( 0 )
{
    //if the folder not exist, create it
    _mkdir( m_folderName.c_str() );
}

const std::string FileNotificationClient::ConstructFileName()
{

    //Append the current date and time
    //boost::gregorian::date curDate = boost::gregorian::day_clock::universal_day();
    boost::posix_time::ptime nowTime = boost::posix_time::second_clock::universal_time();
    std::stringstream ss;
    ss << boost::posix_time::to_iso_string(nowTime).substr( 0, 15 );
    
    std::string fileName( ss.str() );

    //use an intenal counter and the date & time
    char tmp[100] = {0};
    _itoa_s( m_counter, tmp, 10 ); //This won't fail
    m_counter++;
    fileName += tmp;

    fileName += (".txt" );

    return fileName;
}

void FileNotificationClient::Update( const NotificationComposer* composer  )
{
    //open the file stream based on folder name and generated filename
    if( composer->Constructed() )
    {
        std::string fullName = m_folderName + "\\" + ConstructFileName();

        std::ofstream out( fullName.c_str() );
        if( out )
        {
            composer->Stream( out );
            out.flush();
        }
    }
}